# -*- coding: utf-8 -*-

import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import models.milestonePlan as mpm
import models.MPTemplates as MPTm
import models.city as cm

def view( ):
  response = '<h2>View milestone plan templates</h2>\n <table>'
  templates = MPTm.MPTemplateModel.file().split('\n\n')
  for template in templates:
    template = template.split('\n')
    tpl = {}
    tpl['origin'], tpl['destination'], tpl['type'] = template.pop(0).split(',')

    #response+='''<table><tr><td><b>%s</b></td><td><b>%s</b></td><td><b>%s</b></td></tr></table>\n ''' % (tpl['origin'], tpl['destination'], tpl['type'])
    query = cm.CityModel.all()
    orig = query.filter( 'code =', str(tpl['origin']) ).get()
    query = cm.CityModel.all()
    dest = query.filter( 'code =', str(tpl['destination']) ).get()	  
    response+='''<table><tr><td>Origin:</td><td><b>%s</b></td></tr> \n
	<tr><td>Destination:</td><td><b>%s</b></td></tr> \n
	<tr><td>Type:</td><td><b>%s</b></td></tr></table>\n ''' % (
	orig.linkTo(action='show1', text=orig.code) if orig else tpl['origin'],
	dest.linkTo(action='show1', text=dest.code) if dest else tpl['dest'],
	tpl['type'])
	
    response+='''<table><tr><td><i>Time delta</i></td><td><i>City</i></td><td><i>Status</i></td></tr>\n ''' 
    for point in template:
      pointInfo = {}
      pointInfo['timeDelta'], pointInfo['city'], pointInfo['status'] = point.split(',')
      query = cm.CityModel.all()
      city = query.filter( 'code =', str(pointInfo['city']) ).get()
      response+='''<tr><td>%s hours</td><td>%s</td><td>%s</td></tr>\n ''' %(
	  pointInfo['timeDelta'], 
	  city.linkTo(action='show1', text=city.code) if city else str(pointInfo['city']), 
	  pointInfo['status'])

    response += '</table><br/><br/>'

  return response
